<template>
  <div class="list">
    <!-- 活动列表 -->
    <div class="list-container">
      <van-empty v-if="activityList.length === 0" description="暂无活动" />
      <van-radio-group
        v-model="currentSelectIndex"
        v-for="(item, index) in activityList"
        :key="item.id"
      >
        <div class="item">
          <!-- 头部： 按钮和倒计时 -->
          <div class="div1">
            <!-- 禁用按钮： 活动停止、 活动结束 -->
            <van-radio
              :name="index"
              checked-color="orangered"
              :disabled="
                item.activityEnable === 0 ||
                  (!item.distantToStart && !item.distantToEnd)
              "
            ></van-radio>
            <div class="time">
              <span>
                {{
                  item.activityEnable == 1 && item.distantToStart
                    ? "距开始："
                    : ""
                }}
              </span>
              <span>
                {{
                  item.activityEnable == 1 && item.distantToEnd
                    ? "距结束："
                    : ""
                }}
              </span>
              <span>
                {{
                  item.activityEnable == 1 &&
                  !item.distantToStart &&
                  !item.distantToEnd
                    ? "已结束："
                    : ""
                }}
              </span>
              <span>{{ item.activityEnable == 1 ? "" : "已暂停：" }}</span>
              <van-count-down
                :time="
                  item.distantToStart ? item.distantToStart : item.distantToEnd
                "
              >
                <template #default="timeData">
                  <span class="block" v-if="timeData.days > 0">
                    {{
                      timeData.days < 10 ? "0" + timeData.days : timeData.days
                    }}
                  </span>
                  <span class="colon" v-if="timeData.days > 0">天</span>
                  <span class="block">
                    {{
                      timeData.hours < 10
                        ? "0" + timeData.hours
                        : timeData.hours
                    }}
                  </span>
                  <span class="colon">:</span>
                  <span class="block">
                    {{
                      timeData.minutes < 10
                        ? "0" + timeData.minutes
                        : timeData.minutes
                    }}
                  </span>
                  <span class="colon">:</span>
                  <span class="block">
                    {{
                      timeData.seconds < 10
                        ? "0" + timeData.seconds
                        : timeData.seconds
                    }}
                  </span>
                </template>
              </van-count-down>
            </div>
          </div>
          <!-- 中间图片及商品信息 -->
          <div class="div2">
            <img
              v-if="!item.productImg"
              src="~static/coupon/default.png"
              alt="默认图片"
              style="max-height: 0.5rem;"
            />
            <img v-else :src="item.productImg" alt="商品图片" />
            <div class="text">
              <p class="name">{{ item.activityName }}</p>
              <p class="desc">{{ item.description }}</p>
              <p class="amt">
                ￥<b>{{ item.price }}</b>
                <span
                  style="text-decoration-line: line-through;color: #ddd;font-size:0.28rem;"
                  v-if="item.originalPrice"
                >
                  ￥{{ item.originalPrice }}
                </span>
              </p>
            </div>
          </div>
          <!-- 进度条，购买数量。originStock: 总库存  stock ： 剩余库存  -->
          <div class="div3">
            <div class="progress">
              <van-progress
                :percentage="(item.stock / item.originStock) * 100"
                color="orangered"
                :show-pivot="false"
              />
            </div>
            <div class="stepper">
              <van-stepper
                v-model="item.buyCount"
                integer
                button-size="25px"
                @change="changeBuyCount"
              />
            </div>
          </div>
        </div>
      </van-radio-group>
    </div>

    <!-- 选择油站面板 -->
    <van-action-sheet
      v-model="stationShow"
      :actions="stationList"
      @select="onSelect"
    />

    <!-- 提交订单 -->
    <div class="buttonSub" v-if="activityList.length > 0">
      <div class="left">
        <span>合计:</span>
        <span class="amt">￥{{ sumAmt }}</span>
      </div>
      <div class="right">
        <van-button
          type="primary"
          color="orangered"
          size="normal"
          round
          :disabled="sumAmt <= 0 || isDisabled"
          @click="handleSubmit"
          :loading="loading"
          loading-text="支付中..."
          >立即抢购</van-button
        >
      </div>
    </div>

    <!-- 页面loding -->
    <van-overlay
      :show="pageLoading"
    >
      <van-loading style="text-align:center;top: 50%;" type="spinner" />
    </van-overlay>
  </div>
</template>
<script>
import Vue from "vue";
import {
  RadioGroup,
  Radio,
  CountDown,
  Stepper,
  Progress,
  Button,
  ActionSheet,
  Empty,
  Overlay,
  Loading
} from "vant";

Vue.use(Radio);
Vue.use(RadioGroup);
Vue.use(CountDown);
Vue.use(Stepper);
Vue.use(Progress);
Vue.use(Button);
Vue.use(ActionSheet);
Vue.use(Empty);
Vue.use(Overlay);
Vue.use(Loading);

export default {
  name: "SecondKill",
  head() {
    return {
      title: "秒杀"
    };
  },
  data() {
    return {
      currentSelectIndex: "", // 当前选中的活动索引
      activityList: [], // 活动列表
      sumAmt: 0, // 支付金额
      stationShow: false,
      stationList: [],
      currentStationInfo: {},
      loading: false,
      pageLoading: false, // 页面的loading
      isDisabled: false //控制是否禁用点击购买按钮
    };
  },
  created() {
    this.getSecondActivityList();
    this.getStationList();
  },

  watch: {
    // 监听当前选中的活动索引
    currentSelectIndex: {
      async handler(val) {
        let list = this.activityList;
        let index = this.currentSelectIndex; // 当前勾选的活动索引index
        this.getSumAmt(list[index]);
      }
    },
    // 建听活动列表，主要是为了监控购买数量字段值
    activityList: {
      handler(val) {
        let list = this.activityList;
        let index = this.currentSelectIndex; // 当前勾选的活动索引index
        if (list[index]) {
          // 还没有勾选活动时，index时没有了，那么就没有找到对应的信息
          this.getSumAmt(list[index]);
        }
      },
      deep: true
    }
  },
  methods: {
    // 获取秒杀活动列表
    async getSecondActivityList() {
      const res = await this.$axios.$get(
        `/saleActivity/list/${this.enterpriseId}`
      );
      this.activityList = res.data || [];
      // 给每个活动对象添加一个属性,用于记录当前活动的购买数量
      const _this = this;
      this.activityList.forEach(item => {
        _this.$set(item, "buyCount", 1);
      });
    },

    // 获取油站列表
    getStationList() {
      this.pageLoading = true;
      this.$axios
        .$get("/appletSelectStationList", {
          params: { enterpriseId: this.enterpriseId }
        })
        .then(res => {
          this.pageLoading = false;
          if (res.retCode != 0) {
            throw new Error("获取油站失败");
          }
          this.stationList = res.data.stationList || [];
          this.stationList.forEach(item => {
            this.$set(item, "name", item.stationName);
          });
        })
        .catch(err => {
          this.pageLoading = false;
          alert(err);
        });
    },

    // 获取支付价格
    async getSumAmt(item) {
      this.pageLoading = true;
      const res = await this.$axios.$get("/saleActivity/calculateAmt", {
        params: {
          saleActivityId: item.id,
          purchaseNum: item.buyCount
        }
      });
      if (res.retCode === 0) {
        this.sumAmt = parseFloat(res.data.amt);
      }
      this.pageLoading = false;
    },

    // 点击立即抢购按钮
    handleSubmit() {
      this.stationShow = true;
    },

    // 选择油站
    onSelect(stationInfo) {
      console.log(stationInfo);
      this.currentStationInfo = stationInfo;
      this.gotoPay();
      this.stationShow = false;
    },

    // 监控购买数量值发生变化
    changeBuyCount(num) {
      let numStr = String(num);
      if (numStr.length > 10) {
        this.isDisabled = true;
        alert("最大长度为10");
      } else {
        this.isDisabled = false;
      }
    },

    // 拉起支付
    async gotoPay() {
      this.loading = true;
      const _this = this;
      let index = this.currentSelectIndex;
      let obj = this.activityList[index];
      let amt = this.sumAmt;
      let stationId = this.currentStationInfo.stationId;
      const {
        userId,
        mobilePhone,
        blogOpenid
      } = this.$store.state.authen.userInfo;
      console.log("gotoPay:", obj, this.$store);

      // 创建订单
      const orderParams = {
        saleActivityId: obj.id, // 活动id
        amt: amt,
        purchaseNum: obj.buyCount,
        userId: userId,
        mobilePhone: mobilePhone
      };
      let orderInfo = await this.$axios.$post(
        "/saleActivityOrder/createOrder",
        orderParams
      );

      if (orderInfo.retCode === 0) {
        // 拉起支付
        const payParams = {
          aliUserId: "1",
          openId: blogOpenid,
          ordNo: orderInfo.data.orderNo,
          stationId: stationId
        };
        this.$axios
          .$post("/saleActivityOrder/toThirdPay", payParams)
          .then(payInfo => {
            if (payInfo.retCode === 0) {
              console.log("支付信息：", payInfo);
              _this.loading = false;
              const data = payInfo.data;
              if (data.thirdPayment === "5") {
                // 云化支付
                window.location.href = data.redirectUrl;
              } else {
                // 正常拉起微信支付
                WeixinJSBridge.invoke(
                  "getBrandWCPayRequest",
                  {
                    appId: data.payAppId,
                    timeStamp: data.payTimeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    nonceStr: data.paynonceStr, // 支付签名随机串，不长于 32
                    package: data.payPackage, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                    signType: data.paySignType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    paySign: data.paySign // 支付签名
                  },
                  function(res) {
                    if (res.err_msg === "get_brand_wcpay_request:ok") {
                      // 使用以上方式判断前端返回,微信团队郑重提示：
                      //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                      _this.loading = false;
                      _this.$toast("支付成功");
                      _this.$router.replace({
                        path: `/${_this.enterpriseId}/fuel/success?ordNo=${orderInfo.data.orderNo}`
                      });
                    } else {
                      _this.$toast("支付失败，请重试");
                      _this.loading = false;
                    }
                  }
                );
              }
            } else {
              alert(payInfo.message);
              this.loading = false;
            }
          });
      } else {
        console.log("创建订单失败");
        alert("创建订单失败 " + orderInfo.message);
        this.loading = false;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.list {
  width: 100vw;
  margin: auto;
  min-height: 100vh;
  background: rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: auto;
  .list-container {
    width: 90vw;
    margin: auto;
    padding-top: 0.3rem;
    padding-bottom: 0.3rem;
    margin-bottom: 1.5rem;
    .item {
      // display: flex;
      // justify-content: space-between;
      // align-items: center;
      margin-bottom: 0.3rem;
      background: #fff;
      padding: 0.3rem;
      border-radius: 0.1rem;
      .div1 {
        display: flex;
        justify-content: space-between;
        width: 100%;
        align-items: center;
        margin-bottom: 0.2rem;
        .time {
          display: flex;
          align-items: center;
          font-size: 0.28rem;
        }
      }

      .div2 {
        display: flex;
        align-items: center;
        img {
          width: 1.5rem;
          height: 1rem;
        }
        .text {
          flex: 1;
          margin-left: 0.5rem;
          p {
            margin: 0;
            padding: 0;
            margin-bottom: 0.2rem;
          }
          .name {
            font-size: 0.32rem;
            font-weight: 600;
          }
          .desc {
            font-size: 0.28rem;
            color: #999;
          }
          .amt {
            color: red;
            font-size: 0.32rem;
            b {
              font-size: 0.45rem;
            }
          }
        }
      }

      .div3 {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        .progress {
          width: 2rem;
          margin-right: 0.3rem;
          overflow: hidden;
        }
        .stepper {
          // width: 50%;
        }
      }
    }
  }

  // 提交订单按钮
  .buttonSub {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.2rem 0rem;
    background: #fff;
    box-shadow: 0px 0px 1px 0px grey;
    div {
      margin-left: 0.2rem;
      margin-right: 0.2rem;
      font-size: 0.33rem;
    }
    .left {
      font-size: 0.3rem;
      color: red;
      .amt {
        font-size: 0.37rem;
      }
    }
    .van-button {
    }
  }
}

// 时间倒计时样式
.colon {
  display: inline-block;
  margin: 0 4px;
  color: block;
}
.block {
  display: inline-block;
  width: 22px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background-color: gray;
}
</style>
